package com.yxhl.zoume.core.specialcar.presenter;

import android.content.Context;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.yxhl.zoume.R;
import com.yxhl.zoume.ZouMeApplication;
import com.yxhl.zoume.common.presenter.BasePresenter;
import com.yxhl.zoume.common.presenter.IPresenter;
import com.yxhl.zoume.common.ui.view.BaseView;
import com.yxhl.zoume.core.specialcar.model.MarkerCategory;
import com.yxhl.zoume.core.specialcar.model.MarkerType;
import com.yxhl.zoume.core.specialcar.model.SpecialCarPayStatus;
import com.yxhl.zoume.core.specialcar.model.SpecialCarRideStatus;
import com.yxhl.zoume.core.specialcar.view.SpecialCarScheduleMapView;
import com.yxhl.zoume.core.tripsmgmt.presenter.ipresenter.ICommentPresenter;
import com.yxhl.zoume.core.tripsmgmt.view.unit.CommentOnDriverView;
import com.yxhl.zoume.data.http.model.specialcar.SpecialCarOrder;
import com.yxhl.zoume.data.http.model.specialcar.SpecialCarPollingLatLng;
import com.yxhl.zoume.data.http.rest.param.specialcar.SpecialCarPollingParam;
import com.yxhl.zoume.data.http.rest.param.tripsmgnt.CommentDriverParam;
import com.yxhl.zoume.data.http.rest.response.specialcar.SpecialCarPollingResponse;
import com.yxhl.zoume.data.http.rest.response.tirps.CommentDriverResponse;
import com.yxhl.zoume.domain.interactor.ZMSubscriber;
import com.yxhl.zoume.domain.interactor.car.specialcar.SpecialCarPollingUseCase;
import com.yxhl.zoume.domain.interactor.tripsmgmt.CommentDriverUseCase;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

/**
 * Created by sugarya on 16/4/21.
 */
public class SpecialCarScheduleMapPresenter extends BasePresenter implements IPresenter, ICommentPresenter {

    /**
     * 网络请求的轮询周期
     */
    public static final int POLLING_PERIOD = 1000 * 10;
    private static final String TAG = "SpecialSchedulePre";
    @Inject
    SpecialCarPollingUseCase mSpecialCarPollingUseCase;
    @Inject
    CommentDriverUseCase mCommentDriverUseCase;

    private SpecialCarScheduleMapView mSpecialCarScheduleMapView;
    private CommentOnDriverView mCommentOnDriverView;

    private Timer mTimer;
    /**
     * 轮询定时器是否取消标示
     */
    private boolean mIsTimerCancel = false;
    /**
     * 订单预约失败,对话框是否弹出标志
     */
    private boolean mIsFirstTimeRunDispatchFailure = true;

    /**
     * 订单超时,对话框是否弹出标示
     */
    private boolean mIsFirstTimeRunTimeOut = true;

    /**
     * 上一次网络请求得到的乘车状态,默认为初始化状态
     */
    private int mLastRideStatus = SpecialCarRideStatus.ORIGINAL;

    /**
     * MarkerOptions容器
     */
    private ArrayList<MarkerOptions> mMarkerOptionsList;


    @Inject
    public SpecialCarScheduleMapPresenter(Context context) {
        super(context);
    }

    public void startPolling(final String orderId) {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!mIsTimerCancel) {
                    synchronized (SpecialCarScheduleMapPresenter.class) {
                        if (!mIsTimerCancel) {
                            querySpecialCarPollingResult(orderId);
                        }
                    }
                }
            }
        }, 0, POLLING_PERIOD);
    }

    private void querySpecialCarPollingResult(String orderId) {
        SpecialCarPollingParam param = new SpecialCarPollingParam(getMobile(), getToken(), orderId);
        mSpecialCarPollingUseCase.execute(param,new ZMSubscriber<SpecialCarPollingResponse>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onNext(SpecialCarPollingResponse specialCarPollingResponse) {
                        super.onNext(specialCarPollingResponse);
                        if (specialCarPollingResponse != null) {
                            LOG.e(TAG, "specialCarPollingResponse=" + specialCarPollingResponse.toString());
                            String resultMessage = specialCarPollingResponse.getResultMessage();
                            boolean succ = specialCarPollingResponse.isSucc();
                            if (succ) {
                                mSpecialCarScheduleMapView.renderDataOnSuccess(specialCarPollingResponse);

                                updateUIByRideStatus(specialCarPollingResponse);
                            } else {
                                mSpecialCarScheduleMapView.renderDataOnFailure(resultMessage);
                                stopPolling();
                            }
                        }
                    }
                });
    }

    /**
     * 更新乘车状态
     *
     * @param pollingResponse
     */
    public void updateUIByRideStatus(SpecialCarPollingResponse pollingResponse) {
        List<SpecialCarOrder> specialCarOrders = pollingResponse.getOrders();
        if (specialCarOrders != null && specialCarOrders.size() > 0) {
            SpecialCarOrder order = specialCarOrders.get(0);
            if (order != null) {
                int rideStatus = order.getRideStatus();
                String payStatus = order.getPayStatus();
                LOG.e(TAG, "payStatus=" + payStatus + " rideStatus=" + rideStatus);

                if (payStatus.equals("2")) {
                    mSpecialCarScheduleMapView.ShowArrivalDialog(order);
                    stopPolling();
                    return;
                }
                //订单预约失败
                if (order.getAttributesKeys().contains("sor")) {
                    if (mIsFirstTimeRunDispatchFailure) {
                        mSpecialCarScheduleMapView.showSDispatchFailureDialog();
                        mIsFirstTimeRunDispatchFailure = !mIsFirstTimeRunDispatchFailure;
                        stopPolling();
                    }
                } else {
                    switch (rideStatus) {
                        //订单预约中,未派车
                        case SpecialCarRideStatus.DISPATCH:
                            showDispatcherUI(order, payStatus);
                            break;
                        //订单提交成功,正在派车中
                        case SpecialCarRideStatus.UN_GET_IN:
                            showWaittingUI(pollingResponse, order);
                            break;
                        //乘客上车,行程中
                        case SpecialCarRideStatus.PICK_UP:
                            if (payStatus.equals("11")) {
                                showPaymentUI(order);
                            } else {
                                showRunningUI(pollingResponse, order);
                            }
                            break;
                        //已到站,去评论
                        case SpecialCarRideStatus.ARRIVED:
                            showAppraisalUI(order);
                            break;
                        //司机未接到,订单失效
                        case SpecialCarRideStatus.DRIVER_DROP_ORDER:
                            showOrderOutOfDateUI();
                            break;
                        //订单关闭,与订单失效互斥
                        case SpecialCarRideStatus.CLOSE_ORDER:
                            showOrderFinishUI();
                            break;

                    }
                }
            }
        }
    }

    /**
     * 展示支付UI
     *
     * @param order
     */
    private void showPaymentUI(SpecialCarOrder order) {
        mSpecialCarScheduleMapView.showPaymentDialog(order);
        stopPolling();
    }

    /**
     * 展示任务关闭UI
     */
    private void showOrderFinishUI() {
        if (mLastRideStatus <= SpecialCarRideStatus.DRIVER_DROP_ORDER) {
            //设置Toolbar
            mSpecialCarScheduleMapView.setupHeaderStatus(
                    ZouMeApplication.application.getString(R.string.special_car_operation_cancel_trip),
                    ""
            );

            //显示对话框
            mSpecialCarScheduleMapView.showInvalidDataDialog();

            //更新乘车状态
            mLastRideStatus = SpecialCarRideStatus.CLOSE_ORDER;

            stopPolling();
        }
    }

    /**
     * 展示任务失效UI
     */
    private void showOrderOutOfDateUI() {
        if (mLastRideStatus <= SpecialCarRideStatus.ARRIVED) {
            //设置Toolbar
            mSpecialCarScheduleMapView.setupHeaderStatus(
                    ZouMeApplication.application.getString(R.string.route_detail_cancel_charter),
                    ""
            );

            //显示对话框
            mSpecialCarScheduleMapView.showDriverCloseDialog();

            //更新乘车状态
            mLastRideStatus = SpecialCarRideStatus.DRIVER_DROP_ORDER;

            stopPolling();
        }
    }

    /**
     * 展示评价页面
     *
     * @param order
     */
    private void showAppraisalUI(SpecialCarOrder order) {
        if (mLastRideStatus <= SpecialCarRideStatus.PICK_UP) {
            //更新ToolBar
            mSpecialCarScheduleMapView.setupHeaderStatus(
                    ZouMeApplication.application.getString(R.string.route_detail_finish_charter),
                    ""
            );
            if (mLastRideStatus != SpecialCarRideStatus.ORIGINAL) {
                //DriverInfo退出动画
                mSpecialCarScheduleMapView.startExitAnimatorForDriverInfo();
            }

            //评论司机
            mSpecialCarScheduleMapView.ShowArrivalDialog(order);

            //更新乘车状态
            mLastRideStatus = SpecialCarRideStatus.ARRIVED;
        }
    }

    /**
     * 展示行程中UI
     *
     * @param pollingResponse
     * @param order
     */
    private void showRunningUI(SpecialCarPollingResponse pollingResponse, SpecialCarOrder order) {
        if (mLastRideStatus <= SpecialCarRideStatus.UN_GET_IN) {
            //更新ToolBar
            mSpecialCarScheduleMapView.setupHeaderStatus(
                    ZouMeApplication.application.getString(R.string.route_detail_take_charter),
                    ZouMeApplication.application.getString(R.string.special_car_operation_customer_service)
            );
            //更新DriverInfo
            String content = StringUtils.getCalledName(order.getDriverName()) + " " + order.getVehicleNo();
            int judgePoint = (int) pollingResponse.getDriverJudgePoint();
            Log.e(TAG, "updateUIByRideStatus: judgePoint" + judgePoint);
            mSpecialCarScheduleMapView.setupDriverInfoStatus(content, judgePoint, false);

            if (mLastRideStatus != SpecialCarRideStatus.ORIGINAL) {
                //退出ScheduleBar动画
                mSpecialCarScheduleMapView.startExitAnimatorForScheduleBar();
            } else {
                mSpecialCarScheduleMapView.startEnterAnimatorForDriverInfoAndScheduleBar(false);
            }

            //更新乘车状态
            mLastRideStatus = SpecialCarRideStatus.PICK_UP;
        }
    }

    /**
     * 展示等待司机接驾UI
     *
     * @param pollingResponse
     * @param order
     */
    private void showWaittingUI(SpecialCarPollingResponse pollingResponse, SpecialCarOrder order) {
        LOG.e(TAG, "UN_GET_IN");
        //第一次轮询到该状态时
        if (mLastRideStatus <= SpecialCarRideStatus.DISPATCH) {
            /*
                1.更新DriverIno信息
                2.更新Toolbar信息
                3.开启过度动画
                4.更新乘车状态
             */
            String content = StringUtils.getCalledName(order.getDriverName()) + " " + order.getVehicleNo();
            double judgePoint = pollingResponse.getDriverJudgePoint();
            LOG.e(TAG, "judgePoint=" + judgePoint);
            mSpecialCarScheduleMapView.setupDriverInfoStatus(content, judgePoint, true);

            mSpecialCarScheduleMapView.setupHeaderStatus(
                    ZouMeApplication.application.getString(R.string.route_detail_wait_charter),
                    ZouMeApplication.application.getString(R.string.special_car_operation_cancel_trip)
            );
            //true,表示由上一个状态过度来的,则需要开启移除上一个状态出现的行程信息栏动画
            if (mLastRideStatus != SpecialCarRideStatus.ORIGINAL) {
                mSpecialCarScheduleMapView.startExitAnimatorForScheduleBar();
            }

            mSpecialCarScheduleMapView.updateDataBetweenRideStatus(
                    SpecialCarRideStatus.DISPATCH, SpecialCarRideStatus.UN_GET_IN, order);
            mSpecialCarScheduleMapView.startEnterAnimatorForDriverInfoAndScheduleBar(true);

            mLastRideStatus = SpecialCarRideStatus.UN_GET_IN;
        }
    }

    /**
     * 展示等待派车UI
     *
     * @param order
     * @param payStatus
     */
    private void showDispatcherUI(SpecialCarOrder order, String payStatus) {
        if (mLastRideStatus < SpecialCarRideStatus.DISPATCH) {
            //更新Toolbar
            mSpecialCarScheduleMapView.setupHeaderStatus(
                    ZouMeApplication.application.getString(R.string.route_detail_no_charter),
                    ZouMeApplication.application.getString(R.string.special_car_operation_cancel_trip)
            );
            //弹出ScheduleBar动画
            mSpecialCarScheduleMapView.startEnterAnimatorForScheduleBar();

            //更新乘车状态
            mLastRideStatus = SpecialCarRideStatus.DISPATCH;
        }
        //司机拒绝接任务,订单状态回滚到未派车
        else if (mLastRideStatus == SpecialCarRideStatus.UN_GET_IN) {
            //开启ScheduleBar退出动画
            mSpecialCarScheduleMapView.startExitAnimatorForScheduleBar();
            //更新ScheduleBar数据
            mSpecialCarScheduleMapView.updateDataBetweenRideStatus(
                    SpecialCarRideStatus.UN_GET_IN,
                    SpecialCarRideStatus.DISPATCH,
                    order);
            //更新Toolbar
            mSpecialCarScheduleMapView.setupHeaderStatus(
                    ZouMeApplication.application.getString(R.string.route_detail_no_charter),
                    ZouMeApplication.application.getString(R.string.special_car_operation_cancel_trip)
            );
            //开启ScheduleBar进入动画
            mSpecialCarScheduleMapView.startEnterAnimatorForScheduleBar();
            //更新乘车状态
            mLastRideStatus = SpecialCarRideStatus.DISPATCH;
        }

        //订单超时 失效
        if (payStatus.trim().equals(String.valueOf(SpecialCarPayStatus.CANCEL))) {
            if (mIsFirstTimeRunTimeOut) {
                mSpecialCarScheduleMapView.showTimeOutDialog();
                mIsFirstTimeRunTimeOut = !mIsFirstTimeRunTimeOut;
                stopPolling();
            }
        }
    }

    /**
     * 更新地图覆盖物
     *
     * @param aMap
     * @param LatLngList
     * @param eLatLngList
     */
    public void refreshMarkersInMap(AMap aMap,
                                    List<SpecialCarPollingLatLng> LatLngList,
                                    List<SpecialCarPollingLatLng> eLatLngList) {
        if (aMap != null) {
            //清空地图上所有覆盖物
            aMap.clear();
            if (mMarkerOptionsList == null) {
                mMarkerOptionsList = new ArrayList<>();
            }
            mMarkerOptionsList.clear();

            if (LatLngList != null && LatLngList.size() > 0) {
                for (SpecialCarPollingLatLng pollingLatLng : LatLngList) {
                    pollingLatLng.parseLngLat();
                    String locType = pollingLatLng.getLocType();
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions
                            .setFlat(true)
                            .draggable(false)
                            .position(new LatLng(pollingLatLng.getLat(), pollingLatLng.getLng()))
                            .icon(
                                    BitmapDescriptorFactory.fromResource(
                                            getMarkerIconResId(MarkerCategory.DEPART, locType))
                            );
                    mMarkerOptionsList.add(markerOptions);
                }

            }
            if (eLatLngList != null && eLatLngList.size() > 0) {
                for (SpecialCarPollingLatLng pollingELatLng : eLatLngList) {
                    pollingELatLng.parseLngLat();
                    String locType = pollingELatLng.getLocType();
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions
                            .setFlat(true)
                            .draggable(false)
                            .anchor(0.5f, 1f)
                            .position(new LatLng(pollingELatLng.getLat(), pollingELatLng.getLng()))
                            .icon(BitmapDescriptorFactory.fromResource(
                                    getMarkerIconResId(MarkerCategory.ARRIVAL, locType)
                            ));
                    mMarkerOptionsList.add(markerOptions);
                }
            }

            aMap.addMarkers(mMarkerOptionsList, true);
        }
    }

    /**
     * 获取地图覆盖物对应的图标
     *
     * @param category
     * @param locType
     * @return
     */
    public
    @DrawableRes
    int getMarkerIconResId(int category, String locType) {
        if (!TextUtils.isEmpty(locType)) {
            int markerIconResId;
            switch (locType) {
                case MarkerType.USER:
                    markerIconResId = category == MarkerCategory.DEPART
                            ? R.drawable.icon_self_origin : R.drawable.icon_self_dest;
                    break;
                case MarkerType.PARTNER:
                    markerIconResId = category == MarkerCategory.DEPART
                            ? R.drawable.icon_other_origin : R.drawable.icon_other_dest;

                    break;
                case MarkerType.CAR:
                    markerIconResId = category == MarkerCategory.DEPART
                            ? R.drawable.ic_kuaiche_tubiao : 0;
                    break;
                default:
                    markerIconResId = 0;
            }
            return markerIconResId;
        }
        return 0;
    }

    @Override
    public void commentOnDriver(String orderId, int starAmount, String commentMessage) {
        CommentDriverParam commentDriverParam = new CommentDriverParam(
                getMobile(),
                getToken(),
                orderId,
                starAmount,
                commentMessage
        );
        mCommentDriverUseCase.execute(commentDriverParam,new ZMSubscriber<CommentDriverResponse>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mCommentOnDriverView.closeCommentOnCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mCommentOnDriverView.renderCommentOnError("");
                    }

                    @Override
                    public void onNext(CommentDriverResponse commentDriverResponse) {
                        super.onNext(commentDriverResponse);
                        if (commentDriverResponse != null) {
                            boolean succ = commentDriverResponse.isSucc();
                            String resultMessage = commentDriverResponse.getResultMessage();
                            if (succ) {
                                mCommentOnDriverView.renderCommentOnSuccess();
                            } else {
                                mCommentOnDriverView.renderCommentOnError(resultMessage);
                            }
                        }
                    }
                });
    }

    /**
     * 停止轮询
     */
    private void stopPolling() {
        mTimer.cancel();
        mIsTimerCancel = true;
        LOG.e(TAG, "stopPolling");
    }


    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onDestroy() {
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    @Override
    public void attachView(BaseView view) {
        if (view != null) {
            if (view instanceof SpecialCarScheduleMapView) {
                mSpecialCarScheduleMapView = (SpecialCarScheduleMapView) view;
            }
            if (view instanceof CommentOnDriverView) {
                mCommentOnDriverView = (CommentOnDriverView) view;
            }
        }
    }

}
